  <template>
  <!-- 油品发票明细 -->
  <el-dialog title="申请服务费发票" :visible.sync="dialogVisible" :close-on-click-modal="closeModal" :close-on-press-escape="closeEscape" :before-close="close" class="apply-invoice-dialog">
    <div class="apply-invoice-wrapper">
      <!-- form 表单-->
      <el-form :model="invoiceForm" :rules="rules" ref="invoiceForm" label-width="120px">
          <el-form-item label="开票类型:">
            <el-radio-group v-model="invoiceForm.invoiceTypeCode">
              <el-radio label="002">纸质专用发票</el-radio>
              <el-radio label="001">纸质普通发票</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="订单交易时间:">
            <el-date-picker
              v-model="tradeTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="yyyy-MM-dd HH:mm:ss" 
              :default-time="['00:00:00', '23:59:59']"
              @change="changeTime">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="发票金额:" prop="balance">
            <el-input v-model="invoiceForm.balance" disabled></el-input>
            <div class="balance-info">{{balanceInfo}}</div>
          </el-form-item>
          <el-form-item label="发票抬头:" prop="title">
            <el-input v-model="invoiceForm.sellerName" disabled></el-input>
          </el-form-item>
          <el-form-item label="发票内容:" prop="content">
            <!-- <el-input v-model="invoiceForm.content"></el-input> -->
            <span>现代服务*服务费</span>
          </el-form-item>
          <el-form-item label="备注信息:" prop="remarks">
            <el-input type="textarea" v-model="invoiceForm.remarks" placeholder="请输入50字以内" maxlength="50"></el-input>
          </el-form-item>
      </el-form>
      <!-- notice 提示-->
      <div class="invoice-notice">
        <i class="el-icon-bell notice-title">温馨提示</i>
        <div class="notice-item">
          1.订单交易时间为用户下单支付完成时间。
        </div>
        <div class="notice-item">
          2.只能对2019年10月01日之后的订单交易发起线上开票申请，若需要对历史的订单交易申请开票，请联系团油商务同事走线下申请流程。
        </div>
        <div class="notice-item">
          3.请于每天6点至24点在线申请开纸质发票。
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" size="mini" :loading="submitLoading" :disabled="applyDisable" @click="applyInvoice">申请开票</el-button>
    </div>
  </el-dialog>
</template>
<script>
import dialog from '@mix/dialog'
import { getChannelInvoiceInfoApi, applyChannelInvoiceApi, getChannelInvoiceBalacneApi,getAllInvoiceInfoApi } from '@/api/finance'
import moment from 'moment'

export default {
  mixins: [dialog],
  props:{
    invoiceId:[String,Number]
  },
  data(){
    return {
      invoiceForm: {
        invoiceTypeCode:'002',
        balance: 0,
        sellerName:'',
        remarks:''
      },
      tradeTime:'',
      rules:{},
      invoiceInfo: {},
      balanceInfo:'提示：单次申请普票最多1万元，专票最多10万元',
      submitLoading: false 
    }
  },
  created(){
    this.initPage()
  },
  computed:{
    applyDisable(){
      return !(this.invoiceForm.balance > 0)
    }
  },
  methods:{
    initPage () {
      this.getAllInvoice()
    },
    //获取开票相关信息
    async getInvoiceInfo(){
      try{
        const { code, result={} } = await getChannelInvoiceInfoApi()
        if(code !== 200) return
        this.invoiceInfo = result
      }catch(err){
        console.log(err)
      }
    },
    changeTime(value){
      if (value) {
        this.invoiceForm.applyStartTime = value[0]
        this.invoiceForm.applyEndTime = value[1]
        this.getInvoiceBlance(value[0],value[1])
      } else {
        this.invoiceForm.applyStartTime = ''
        this.invoiceForm.applyEndTime = ''
      }
    },
    //获取金额
    async getInvoiceBlance(startTime,endTime){
       try {
        const data = {
          applyStartTime: startTime,
          applyEndTime: endTime
        }
        const { code, result = '0.00' } = await getChannelInvoiceBalacneApi(data)
        if(code !== 200) return
        this.invoiceForm.balance = result
      } catch (err) {
        console.log(err)
      }
    },
    //获取发票抬头
    async getAllInvoice(){
      try{
        let needInvoice = {}
        const {code, result = []} = await getAllInvoiceInfoApi()
        if( code !==200 ) return
        needInvoice = this.setDefaultInvoiceOrAddress(result)
        this.invoiceForm.sellerName = needInvoice.sellerName || ''    //发票抬头
        this.invoiceForm.id = needInvoice.id || ''     //发票id
      }catch(e){
        console.log(e)
      }
    },
    //获取默认的发票或地址，若没有默认，取数组第一项
    setDefaultInvoiceOrAddress(arr = []){
      let needArr = []
      if(arr && arr.length){
        needArr = arr.filter((item)=>{
          return item.type === 0
        })
      }
      return needArr.length ? needArr[0] : {}
    },
    //申请开票
    applyInvoice(){
      if(!this.invoiceForm.sellerName){
        this.$message.warning('请先设置默认发票信息')
        return
      }
      if(!this.invoiceForm.applyStartTime){
        this.$message.warning('请选择时间')
        return
      }
      if(!this.checkBlance(this.invoiceForm.invoiceTypeCode,Number(this.invoiceForm.balance))){
         return
      }
      this.$refs['invoiceForm'].validate(async (valid) => {
        if (valid) {
          this.submitLoading = true
          const data = {
            ...this.invoiceForm,
            applyStartTime: moment(this.invoiceForm.applyStartTime).format('YYYY-MM-DD'),
            applyEndTime: moment(this.invoiceForm.applyEndTime).format('YYYY-MM-DD')
          }
          //submit
          const { code } = await applyChannelInvoiceApi(data)
          if(code !== 200){
            this.submitLoading =false 
            return
          }  
          this.$emit('close')
          this.submitLoading = false
          this.$message.success('申请成功')
        } 
      });
    },
    checkBlance(type,balance){
      let pass = true
      //纸质专用发票 002  普通001
      switch(type){
        case '001':
          if( balance > 10000){
            this.$message.warning('单次申请普票最多1万')
            pass = false
          }
          break
        case '002': 
          if( balance > 100000){
            this.$message.warning('单次申请专票最多10万')
            pass = false
          }  
          break  
      }
      return pass
    }
  }
}
</script>
<style lang="less" scoped>
.apply-invoice-wrapper{
  padding: 0 20px;
  .el-form-item {
    margin-bottom: 18px;
  }
  .balance-info{
    font-size: 12px;
    color: #A6A6A6;
  }
  .invoice-notice{
    color: #A6A6A6;
    font-size: 12px;
    .notice-title{
      color: #666;
      font-size: 14px;
      margin-bottom: 8px;
    }
    .notice-item{
      margin-bottom: 5px;
    }
  }
}
</style> 